package com.mytx.live.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mytx.common.annotation.SerializedField;
import com.mytx.common.constant.Constant;
import com.mytx.common.pojo.CommonResult;
import com.mytx.common.pojo.RedisLock;
import com.mytx.common.utils.DateUtils;
import com.mytx.common.utils.EntityUtils;
import com.mytx.common.utils.IDUtils;
import com.mytx.live.utils.PayUtils;
import com.mytx.pojo.LiveRecordExample;
import com.mytx.pojo.LiveRoomExample;
import com.mytx.pojo.UserExample;
import com.mytx.live.service.LiveService;
import com.mytx.mapper.*;
import com.mytx.pojo.*;
import org.omg.PortableInterceptor.INACTIVE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.DefaultTransactionStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@SuppressWarnings({"SpringJavaInjectionPointsAutowiringInspection", "Duplicates"})
@RestController
public class LiveController implements LiveService {
    private static Logger logger = LoggerFactory.getLogger(LiveController.class);
    @Autowired
    LiveRoomMapper liveRoomMapper;
    @Autowired
    LiveRecordMapper liveRecordMapper;

    @Autowired
    UserMapper userMapper;
    @Autowired
    RewardMapper rewardMapper;

    @Autowired
    MulctMapper mulctMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;

    @Autowired
    DonationMapper donationMapper;

    @Autowired
    TopicMapper topicMapper;


    @Autowired
    MyFileMapper myFileMapper;
    @Autowired
    CouponMapper couponMapper;

    @Autowired
    PresentMapper presentMapper;


    @Value("${live_rate}")//直播收益平台分成比率
            Double liveProfitRate;
    @Value("${start_live_duration}")//开始直播时长基数
            int startLiveDuration;

    @RequestMapping(value = "/createLiveRoom", method = RequestMethod.POST)
    public CommonResult createLiveRoom(@RequestBody LiveRoom liveRoom) {
        String uId = request.getHeader("uId");
        logger.info("createLiveRoom:uid:{}", uId);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        liveRoom.setId(uuid);
        int i = liveRoomMapper.insertSelective(liveRoom);
        return CommonResult.ok(uuid);
    }


    @RequestMapping(value = "/deleteLiveRoom", method = RequestMethod.POST)
    public CommonResult deleteLiveRoom(@RequestBody Map<String, Object> info) {
        String id = info.get("id") + "";
        int i = liveRoomMapper.deleteByPrimaryKey(id);
        return CommonResult.ok();
    }


    @RequestMapping(value = "/updateLiveRoom", method = RequestMethod.POST)
    public CommonResult updateLiveRoom(@RequestBody Map<String, Object> info) {
        JSONObject jsonObject = new JSONObject(info);
        LiveRoom liveRoom = jsonObject.getObject("liveRoom", LiveRoom.class);
        liveRoomMapper.updateByPrimaryKeySelective(liveRoom);
        return null;
    }

    @Transactional
    @RequestMapping(value = "/startLive", method = RequestMethod.POST)
    public CommonResult startLive(@RequestBody LiveRoom liveRoom) {
        String uId = request.getHeader("uId");
        String liveRoomId = liveRoom.getId();
        RedisLock redisLock = new RedisLock(redisTemplate, Constant.LIVE_ROOM_LOCK + liveRoomId, 1);
        try {
            //如果没获取到锁，说明别人正在设置直播间信息，直接返回错误
            if (!redisLock.lock()) {
                return CommonResult.build(Constant.LIVE_ROOM_HAD_STARTED, "其他主播捷足先登了");
            }
            //Integer status = null;
            LiveRoom oldLiveRoom = new LiveRoom();
            Map entries = redisTemplate.opsForHash().entries(Constant.LIVE_ROOM + liveRoomId);
            if (entries.size() != 0) {
                oldLiveRoom = JSONObject.parseObject(JSON.toJSONString(entries), LiveRoom.class);
                if (oldLiveRoom.getStatus() != null && oldLiveRoom.getStatus() == Constant.LIVE_ROOM_STATUS_STARTED) {
                    return CommonResult.build(Constant.LIVE_ROOM_HAD_STARTED, "其他主播捷足先登了");
                }
            }

            int totalDuration = startLiveDuration;
            Double donationToTopic = donationMapper.queryUserDonationToTopic(uId, liveRoomId);
            if (donationToTopic != null) {//额外根据捐赠金额，1毛钱增加1s，
                totalDuration = (int) (totalDuration + donationToTopic * 10);
            }
            //生成直播记录
            LiveRecord liveRecord = new LiveRecord();
            liveRecord.setId(IDUtils.genUUID());
            liveRecord.setAnchorId(uId);
            liveRecord.setCreated(new Date());
            liveRecord.setrId(liveRoomId);
            liveRecord.setDuration(totalDuration);
            liveRecord.setStatus(Constant.NOT_BALANCE_ACCOUNTS);
            //设置主播id，直播记录id、直播间状态
            liveRoom.setrId(liveRecord.getId());
            liveRoom.setAnchorId(uId);
            liveRoom.setStatus(Constant.LIVE_ROOM_STATUS_STARTED);
            liveRoom.setUpdated(new Date());
            liveRoom.setAdvertisement(oldLiveRoom.getAdvertisement());//把广告信息设置进直播间,可能是空的
            //保存直播记录到mysql
            liveRecordMapper.insertSelective(liveRecord);
            //更新直播间状态到mysql
            liveRoomMapper.updateByPrimaryKeySelective(liveRoom);
            //保存直播间信息和直播记录信息到redis，方便进入直播间的用户获取这两个信息

            liveRoom.setLiveRecord(liveRecord);
            Map entriesUser = redisTemplate.opsForHash().entries(Constant.USER_SESSION + uId);
            User user = new User();
            user.setuId(uId);
            user.setAvatar((String) entriesUser.get("avatar"));
            user.setUsername((String) entriesUser.get("username"));
            liveRoom.setAnchor(user);

            redisTemplate.opsForHash().putAll(Constant.LIVE_ROOM + liveRoomId, EntityUtils.objectToMap_v1(liveRoom));

            redisTemplate.opsForHash().increment(Constant.LIVE_RECORD + liveRecord.getId(), "duration", totalDuration);//在开始直播的时候，计算获取直播时长，并保存进redis

            //通知直播间直播马上开始
//            JSONObject info = new JSONObject();
//            info.put("liveRoomId", liveRoomId);
//            info.put("liveRoom", liveRoom);
            // redisTemplate.convertAndSend(Constant.NOTIFY_LIVE_TO_START, info);
            return CommonResult.ok(liveRecord);


        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.build(Constant.UNKNOWN_ERROR, "未知错误");
        } finally {
            redisLock.unlock();
        }

    }


    @RequestMapping(value = "/stopLive", method = RequestMethod.POST)
    public CommonResult stopLive(@RequestBody LiveRoom liveRoom) {
        String uId = request.getHeader("uId");
        String liveRoomId = liveRoom.getId();
        logger.info("stopLive:停止直播,uId:{},liveRoomId:{},liveRecordId:{}", uId, liveRoomId, liveRoom.getrId());

        //如果执行停止的不是直播者或管理员，视为非法请求
//        if (!StringUtils.equals(liveRoom.getAnchorId(), uId) && !StringUtils.equals(liveRoom.getAdminId(), uId)) {
//            logger.error("stopLive:停止直播非法访问,uId:{},liveRoomId:{}", uId, liveRoomId);
//            return CommonResult.build(Constant.UNKNOWN_ERROR, "未知错误");
//        }
        //更新直播间状态为停止直播状态
        redisTemplate.opsForHash().put(Constant.LIVE_ROOM + liveRoomId, "status", Constant.LIVE_ROOM_STATUS_STOPED);
//        JSONObject info = new JSONObject();
//        info.put("liveRoomId", liveRoomId);
        //通知直播间，直播停止
        // redisTemplate.convertAndSend(Constant.NOTIFY_LIVE_TO_STOP, info);

        //从Redis中获取当场直播的直播记录，如有打赏等，都在里面
        LiveRecord liveRecord = new LiveRecord();
        Map entries = redisTemplate.opsForHash().entries(Constant.LIVE_RECORD + liveRoom.getrId());
        if (entries.size() != 0) {
            liveRecord = JSONObject.parseObject(JSONObject.toJSONString(entries), LiveRecord.class);
        }
        if (liveRecord.getReward() == null && liveRecord.getMulct() == null) {
            redisTemplate.delete(Constant.LIVE_RECORD + liveRoom.getrId());
        }
//        if (liveRecord.getReward() != null) {
//            liveRecord.setUserProfit(liveRecord.getReward().multiply(new BigDecimal(liveProfitRate)).setScale(2,BigDecimal.ROUND_DOWN));
//        }
        return CommonResult.ok(liveRecord);
    }

    @Transactional
    @PostMapping("/handleLiveProfit")
    public CommonResult handleLiveProfit(@RequestBody LiveRecord liveRecord) {
        String uId = request.getHeader("uId");
        String liveRecordId = liveRecord.getId();
        BigDecimal newUserProfit = BigDecimal.ZERO;
        Map entries = redisTemplate.opsForHash().entries(Constant.LIVE_RECORD + liveRecordId);
        if (entries.size() != 0) {

            LiveRecord redisLiveRecord = JSONObject.parseObject(JSONObject.toJSONString(entries), LiveRecord.class);

            liveRecord.setReward(redisLiveRecord.getReward());
            liveRecord.setProfitRate(liveProfitRate);//直播收益分成可能是浮动的，所以应该记录当前分成比例进数据库，方便以后查询之用
            //保留2位小数
            BigDecimal userProfit = liveRecord.getReward().multiply(new BigDecimal(liveProfitRate)).setScale(2, BigDecimal.ROUND_DOWN);
            liveRecord.setUserProfit(userProfit);
            liveRecord.setPlatformProfit(liveRecord.getReward().subtract(userProfit));
            liveRecord.setMulct(redisLiveRecord.getMulct());
            BigDecimal donationAmount = BigDecimal.ZERO;
            if (liveRecord.getDonationAmount() != null) {
                donationAmount = liveRecord.getDonationAmount();
                if (donationAmount.compareTo(liveRecord.getUserProfit()) > 0) {
                    logger.error("handleLiveProfit:捐赠金额大于用户收益，uId:{},UserProfit:{},donationAmount:{}", uId, liveRecord.getUserProfit(), donationAmount);
                    return CommonResult.build(Constant.STOP_LIVE_DONATION_ERROR_USER_PROFIT_NOT_ENOUGH, "非法访问");
                }
                Donation donation = new Donation();
                donation.setId(IDUtils.genOrderItemId());
                donation.setmId(uId);
                donation.setoId(liveRecord.getrId());
                donation.setAmount(donationAmount);
                donation.setType(Constant.DONATION_TYPE_LIVE_PROFIT);
                donation.setStatus(Constant.DONATION_STATUS_COULD_NOT_REVOKE);
                donation.setCreated(new Date());
                donationMapper.insertSelective(donation);
                liveRecord.setdId(donation.getId());
            }
            //结算当场直播的收益
            newUserProfit = liveRecord.getUserProfit().subtract(donationAmount);
            //如果当场直播有打赏或者惩罚，12小时后清除缓存，以后根据实际情况做修改，也许可以直接清除，而不用等12小时
            redisTemplate.expire(Constant.LIVE_RECORD  + liveRecordId, 12, TimeUnit.HOURS);
        } else {
            //如果打赏和惩罚都没有，直接删除直播记录的缓存
            redisTemplate.delete(Constant.LIVE_RECORD + liveRecordId);
        }
        //更新当场直播的记录到mysql
        liveRecord.setUserProfit(newUserProfit);
        liveRecord.setStatus(Constant.HAD_BALANCE_ACCOUNTS);
        liveRecord.setUpdated(new Date());
        liveRecordMapper.updateByPrimaryKeySelective(liveRecord);
        if (newUserProfit.compareTo(BigDecimal.ZERO) > 0) {

            //持久化到mysql
            BigDecimal mysqlBalance = userMapper.incrementBalance(uId, newUserProfit);
            //缓存到Redis
            redisTemplate.opsForHash().put(Constant.USER_SESSION + uId, "balance", mysqlBalance);
            logger.info("handleLiveProfit:余额增加 uId:{},amount:{},balance:{}", uId, newUserProfit, mysqlBalance);
            return CommonResult.ok(mysqlBalance);
        }
        return CommonResult.ok();
    }

    @RequestMapping(value = "/reward", method = RequestMethod.POST)
    public CommonResult reward(@RequestBody JSONObject body) {
        Reward reward = body.getObject("reward", Reward.class);

        String uId = request.getHeader("uId");
        String liveRecordId = reward.getrId();
        logger.info("reward:uId:{},liveRoomId:{},liveRecordId:{}", uId, reward.getlId(), liveRecordId);
        reward.setId(IDUtils.genUUID());
        BigDecimal rewardAmount = reward.getAmount();
        String payPassword = body.getString("payPassword");
        User user = getUser(uId);
        RedisLock redisLock = new RedisLock(redisTemplate, "USER_SESSION_LOCK:" + uId);
        try {
            if (!redisLock.lock()) {
                return CommonResult.build(Constant.GET_LOCK_FAIL, "获取用户锁失败");
            }
            CommonResult commonResult = PayUtils.payPrepare(payPassword, rewardAmount, user);
            if (commonResult != null) {
                return commonResult;
            }
            reward.setuId(uId);
            reward.setCreated(new Date());
            rewardMapper.insertSelective(reward);
            //减少少用户余额
            //持久化到mysql
            BigDecimal mysqlBalance = userMapper.reduceBalance(uId, rewardAmount);
            //更新redis中用户余额
            redisTemplate.opsForHash().put(Constant.USER_SESSION + uId, Constant.BALANCE, mysqlBalance);
            logger.info("reward:余额减少 uId:{},amount:{},balance:{}", uId, rewardAmount, mysqlBalance);

            //以直播记录作为key,记录当场直播的打赏金额
            redisTemplate.opsForHash().increment(Constant.LIVE_RECORD + liveRecordId, "reward", rewardAmount.doubleValue());
            //根据直播间人数和惩罚金额计算直播时长增量
            int durationIncrement = getDurationIncrement(rewardAmount.doubleValue(), reward.getAudienceSize());
            Long totalDuration = redisTemplate.opsForHash().increment(Constant.LIVE_RECORD + liveRecordId, "duration", durationIncrement);
            JSONObject info = new JSONObject();
            info.put("balance", mysqlBalance);
            info.put("duration", totalDuration);//当场直播时长
//            User newUser = new User();
//            newUser.setuId(uId);
//            newUser.setUsername(user.getUsername());
//            newUser.setAvatar(user.getAvatar());
//            reward.setUser(newUser);
            // info.put("reward", reward);
            //  redisTemplate.convertAndSend(Constant.NOTIFY_LIVE_RECEIVED_REWARD, info);

            return CommonResult.ok(info);
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("打赏出错" + uId, e.getMessage());
            return CommonResult.build(Constant.UNKNOWN_ERROR, "未知错误");

        } finally {
            redisLock.unlock();
        }

    }


    @Transactional
    @RequestMapping(value = "/mulct", method = RequestMethod.POST)
    public CommonResult mulct(@RequestBody JSONObject body) {
        String uId = request.getHeader("uId");
        Mulct mulct = body.getObject("mulct", Mulct.class);
        logger.info("reward:uId:{},liveRoomId:{},liveRecordId:{}", uId, mulct.getlId(), mulct.getrId());
        mulct.setId(IDUtils.genUUID());
        BigDecimal mulctAmount = mulct.getAmount();
        String payPassword = body.getString("payPassword");
        User user = getUser(uId);
        RedisLock redisLock = new RedisLock(redisTemplate, "USER_SESSION_LOCK:" + uId);
        try {
            if (!redisLock.lock()) {
                return CommonResult.build(Constant.GET_LOCK_FAIL, "获取用户锁失败");
            }

            CommonResult commonResult = PayUtils.payPrepare(payPassword, mulctAmount, user);
            if (commonResult != null) {
                return commonResult;
            }
            //完善mulct内容，并保存到mysql
            mulct.setuId(uId);
            mulct.setCreated(new Date());
            mulct.setStatus(0);//表示此笔平台收益，尚未支取，
            mulctMapper.insertSelective(mulct);
            //减少用户余额
            //持久化到mysql
            BigDecimal mysqlBalance = userMapper.reduceBalance(uId, mulctAmount);
            //更新到redis
            redisTemplate.opsForHash().put(Constant.USER_SESSION + uId, Constant.BALANCE, mysqlBalance);
            logger.info("mulct:余额减少 uId:{},amount:{},balance", uId, mulctAmount, mysqlBalance);
            //以直播记录作为key,累加金额的方式记录当场直播点踩(惩罚)的金额
            redisTemplate.opsForHash().increment(Constant.LIVE_RECORD + mulct.getrId(), "mulct", mulctAmount.doubleValue());
            //根据直播间人数和惩罚金额计算直播时长增量
            // int durationIncrement = getDurationIncrement(mulctAmount, mulct.getAudienceSize());
            int durationIncrement = mulctAmount.multiply(new BigDecimal(100)).intValue();
            Long totalDuration = redisTemplate.opsForHash().increment(Constant.LIVE_RECORD + mulct.getrId(), "duration", -durationIncrement);//减少直播总时长
            JSONObject info = new JSONObject();
            info.put("balance", mysqlBalance);
            info.put("duration", totalDuration);//当场直播时长
            // info.put("mulct", mulct);目前app 端用不着返回mulct 数据，如果后续app 丰富了点踩的内容，比如丢臭鸡蛋，烂白菜等，那就需要返回对应的mulct,
            // redisTemplate.convertAndSend(Constant.NOTIFY_LIVE_RECEIVED_MULCT, info);
            return CommonResult.ok(info);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return CommonResult.build(Constant.UNKNOWN_ERROR, "未知错误");
        } finally {
            redisLock.unlock();
        }

    }

    @RequestMapping(value = "/getLiveRoom", method = RequestMethod.POST)
    public CommonResult getLiveRoom(@RequestBody Map<String, Object> info) {
        int page = 1;
        int size = 20;
        if (info.containsKey("page")) {
            page = (int) info.get("page");
        }
        if (info.containsKey("size")) {
            size = (int) info.get("size");
        }
        LiveRoomExample example = new LiveRoomExample();
        PageHelper.startPage(page, size);
        List<LiveRoom> liveRooms = liveRoomMapper.selectByExample(example);
        PageInfo<LiveRoom> liveRoomPageInfo = new PageInfo<>(liveRooms);

        for (LiveRoom liveRoom : liveRooms) {
            String liveRoomId = liveRoom.getId();
            // TODO: 2019/6/16 以下两个方法都可以获取直播间人数
            // Object audienceSize = redisTemplate.opsForHash().get(Constant.LIVE_ROOM + liveRoomId, "audienceSize");
            Long audienceSize = redisTemplate.opsForList().size(Constant.LIVE_ROOM_MEMBER + liveRoomId);
            liveRoom.setAudienceSize(Math.toIntExact(audienceSize));
        }
        return CommonResult.ok(liveRoomPageInfo);
    }

    /**
     * 进入直播间做直播状态查询
     *
     * @param roomId
     * @return 返回直播间信息
     */

    @Override
    @RequestMapping(value = "/queryLiveRoom", method = RequestMethod.POST)
    @SerializedField(encrypt = false)
    public CommonResult queryLiveRoom(@RequestBody String roomId) {
        String uId = request.getHeader("uId");
        Map entries = redisTemplate.opsForHash().entries(Constant.LIVE_ROOM + roomId);
        if (entries.size() > 1) {//不能是!=0，因为可能出现size等于1的情况，里面只有直播间对应的 广告位id,因为在生成广告位的定时任务中，会保存进redis
            if (entries.containsKey("coupon")) {

                JSONObject coupon = (JSONObject) entries.get("coupon");
                String parentCouponId = coupon.getString("id");
                Boolean member = redisTemplate.opsForSet().isMember(Constant.COUPON_RECEIVED_RECORD + parentCouponId, uId);
                //如果已经领取过该一对多红包，那么就去mysql 查询出领取的子红包，传给app
                if (member) {
//                    Coupon childCoupon = couponMapper.selectChildCoupon_v1(parentCouponId, uId);
//                    childCoupon.setParentId(parentCouponId);
                    coupon.put("status", Constant.COUPON_STATUS_RECEIVED);
                    entries.put("coupon", coupon);
                }
            }
            List<String> memberIdList = getLiveRoomMemberList(roomId);
            entries.put("memberIdList", memberIdList);
            return CommonResult.ok(entries);
        }
        LiveRoom liveRoom = liveRoomMapper.selectByPrimaryKey(roomId);
        redisTemplate.opsForHash().putAll(Constant.LIVE_ROOM + roomId, EntityUtils.objectToMap_v1(liveRoom));
        List<String> memberIdList = getLiveRoomMemberList(roomId);
        liveRoom.setMemberIdList(memberIdList);
        return CommonResult.ok(liveRoom);

    }

    private List<String> getLiveRoomMemberList(@RequestBody String roomId) {
        String key = Constant.LIVE_ROOM_MEMBER + roomId;
        Long size = redisTemplate.opsForList().size(key);
        List<String> memberIdList = null;
        if (size != null && size > 0) {
            memberIdList = redisTemplate.opsForList().range(key, 0, size - 1);
        }
        return memberIdList;
    }

    @SerializedField(encrypt = false)
    @RequestMapping(value = "/queryAnchorGoods", method = RequestMethod.POST)
    public CommonResult queryAnchorGoods(@RequestBody String uId) {
        TopicExample example = new TopicExample();
        TopicExample.Criteria criteria = example.createCriteria();
        criteria.andUIdEqualTo(uId);
        //criteria.andTypeBetween(Constant.TOPIC_TYPE_AUCTION, Constant.TOPIC_TYPE_GOODS);
        List<Topic> topicList = topicMapper.selectByExample(example);

        return CommonResult.ok(topicList);
    }


    @Override
    @RequestMapping(value = "/createLiveRecord", method = RequestMethod.POST)
    public CommonResult createLiveRecord(@RequestBody Map<String, Object> info) {
        JSONObject jsonObject = new JSONObject(info);
        LiveRecord liveRecord = jsonObject.getObject("liveRecord", LiveRecord.class);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        liveRecord.setId(uuid);
        liveRecordMapper.insertSelective(liveRecord);
        return CommonResult.ok(uuid);
    }

    /**
     * 聊天室批量查询用户信息
     *
     * @param ids
     * @return
     */
    @Override
    @RequestMapping(value = "/getChannelUsersInfo", method = RequestMethod.POST)
    public CommonResult getChannelUsersInfo(@RequestBody List<String> ids) {
//        JSONObject jsonObject = new JSONObject(info);
//        List<String> ids = jsonObject.getJSONArray("ids").toJavaList(String.class);

        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUIdIn(ids);
        List<User> tbUsers = userMapper.selectByExample(example);
        return CommonResult.ok(tbUsers);
    }

    @Override
    @RequestMapping(value = "/updateLiveRecord", method = RequestMethod.POST)
    public CommonResult updateLiveRecord(@RequestBody Map<String, Object> info) {
        JSONObject jsonObject = new JSONObject(info);
        LiveRecord liveRecord = jsonObject.getObject("liveRecord", LiveRecord.class);
        liveRecordMapper.updateByPrimaryKeySelective(liveRecord);
        return CommonResult.ok();
    }

    @Override
    @RequestMapping(value = "/getLiveRecord", method = RequestMethod.POST)
    public CommonResult getLiveRecord(@RequestBody Map<String, Object> info) {
        String uId = request.getHeader("uId");
        int page = 1;
        int size = 20;
        if (info.containsKey("page")) {
            page = (int) info.get("page");
        }
        if (info.containsKey("size")) {
            size = (int) info.get("size");
        }
        //根据用户id查询直播记录
        LiveRecordExample example = new LiveRecordExample();
        LiveRecordExample.Criteria criteria = example.createCriteria();
        criteria.andAnchorIdEqualTo(uId);
        PageHelper.startPage(page, size);
        List<LiveRecord> liveRecords = liveRecordMapper.selectByExample(example);
        PageInfo<LiveRecord> liveRecordPageInfo = new PageInfo<>(liveRecords);
        return CommonResult.ok(liveRecordPageInfo);

    }


    @GetMapping("getPresent")
    @SerializedField(encrypt = false)
    public CommonResult getPresent() {

        List<Present> presents = presentMapper.selectAllPresent();

        return CommonResult.ok(presents);

    }

    /**
     * 根据直播间人数和惩罚金额计算直播时长增量
     * 这个算法后面根据实际清空修改，，暂时这样
     *
     * @param amount
     * @param audienceSize
     * @return
     */
    private int getDurationIncrement(Double amount, Integer audienceSize) {
        int durationIncrement = (int) (amount * 100);//1分钱1秒钟
        //根据直播间人数做调整
        if (audienceSize < 10) {//人数少于10.一分钱增加10s
            durationIncrement = durationIncrement * 10;
        } else if (audienceSize < 30) {
            durationIncrement = durationIncrement * 8;
        } else if (audienceSize < 50) {
            durationIncrement = durationIncrement * 6;
        } else if (audienceSize < 100) {
            durationIncrement = durationIncrement * 2;
        } else if (audienceSize < 200) {

        } else if (audienceSize < 300) {
            durationIncrement = (int) (durationIncrement * 0.6);
        } else if (audienceSize < 500) {
            durationIncrement = (int) (durationIncrement * 0.4);
        } else if (audienceSize < 800) {
            durationIncrement = (int) (durationIncrement * 0.2);
        } else if (audienceSize < 1500) {
            durationIncrement = (int) (durationIncrement * 0.1);
        } else if (audienceSize < 2000) {
            durationIncrement = (int) (durationIncrement * 0.08);
        } else if (audienceSize > 3000) {
            durationIncrement = (int) (durationIncrement * 0.05);
        }
        if (durationIncrement <= 0) {
            durationIncrement = 1;
        }
        return durationIncrement;
    }

    private User getUser(String uId) {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(Constant.USER_SESSION + uId);
        if(entries.isEmpty()){
            return  userMapper.selectByPrimaryKey(uId);
        }
        return JSONObject.parseObject(JSONObject.toJSONString(entries), User.class);
    }

}
